package com.hzya.frame.utils.core.tree;

import com.hzya.frame.utils.core.entity.BaseEntity;

import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class TreeNode extends BaseEntity{
  private static TreeNodeComparator comparator = new TreeNodeComparator();
  private Long id;
  private String text;
  private String state;
  private String url;
  private Boolean checked = Boolean.FALSE;
  private Object attributes;
  private Long parentId;
  private List<TreeNode> children = new LinkedList();

  public Object getAttributes()
  {
    return this.attributes;
  }

  public void setAttributes(Object attributes) {
    this.attributes = attributes;
  }

  public TreeNode(Long id)
  {
    this.id = id;
  }

  public TreeNode()
  {
  }

  public String getText()
  {
    return this.text;
  }

  public void setText(String text) {
    this.text = text;
  }

  public String getState() {
    return this.state;
  }

  public void setState(String state) {
    this.state = state;
  }

  public String getUrl() {
    return this.url;
  }

  public void setUrl(String url) {
    this.url = url;
  }

  public List<TreeNode> getChildren()
  {
    return this.children;
  }

  public void setChildren(List<TreeNode> children) {
    this.children = children;
  }

  public Long getId() {
    return this.id;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public Boolean getChecked() {
    return this.checked;
  }

  public void setChecked(Boolean checked) {
    this.checked = checked;
  }

  public Long getParentId() {
    return this.parentId;
  }

  public void setParentId(Long parentId) {
    this.parentId = parentId;
  }

  public static TreeNode buildTree(TreeNode root, Map<Long, TreeNode> mapped)
  {
    Set keys = mapped.keySet();
    Iterator it = keys.iterator();
    while (it.hasNext()) {
      TreeNode node = (TreeNode)mapped.get(it.next());
      if (node.getParentId() != null) {
        TreeNode parent = (TreeNode)mapped.get(node.getParentId());
        if (parent != null)
        {
          parent.getChildren().add(node);
        }
        else
          root.getChildren().add(node);
      }

    }

    mapped.put(root.getId(), root);

    Collections.sort(root.getChildren(), comparator);
    return root;
  }
}